package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.Order;
import com.example.repository.StockRepository;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * datetime : 2020/10/7 8:12
 * author : shenxiang
 */
@Controller
@RequestMapping("/seckill")
public class IndexController {

    @Autowired
    private StockRepository stockRepository;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 秒杀界面
     * @param model
     * @return
     */
    @RequestMapping("/")
    public ModelAndView index(ModelAndView model){
//        jedisCluster.set("name","测试名称");
//        jedisCluster.incr("count");
//        System.out.println(jedisCluster.get("name"));
//        System.out.println(jedisCluster.get("count"));
        model.addObject("currentStock",stockRepository.getStock());
        model.setViewName("index");
        return model;
    }

    /**
     * 等待付款界面
     * @param model
     * @return
     */
    @RequestMapping("/awaitPay")
    public ModelAndView awaitPay(ModelAndView model,HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        if(StringUtils.isEmpty(orderId) || !stockRepository.existsOrderNo(orderId)){
            model.setViewName("order_not_found");
        }else{
            // 查缓存中是否存在此订单，不存在也跳转到订单未发现页面
            model.setViewName("await_pay");
            model.addObject("orderId",orderId);
        }
        return model;
    }

    @RequestMapping("/payedSuccess")
    public ModelAndView payedSuccess(ModelAndView model,HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        if(StringUtils.isEmpty(orderId) || !stockRepository.existsOrderNo(orderId)){
            model.setViewName("order_not_found");
        }else{
            // 支付成功缓存中是否存在此订单
            //if (stockRepository.existsPayedByOrderNo(orderId)) {
                model.addObject("orderId", orderId);
                model.setViewName("payed_success");
            //}
        }
        return model;
    }

    /**
     * 获取当前库存
     * @return
     */
    @RequestMapping("/getStock")
    @ResponseBody
    public Map<String,Object> getStock(){
        Map<String,Object> rs = new HashMap<>();
        rs.put("code",0);
        rs.put("msg","获取成功");
        rs.put("data",stockRepository.getStock());
        return rs;
    }

    @RequestMapping("/create_order")
    @ResponseBody
    public Map<String,Object> createOrder(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> rs = new HashMap<>();
        // 真实系统中,用户信息一般通过sessionid去获取
        Integer userId = 151536466;
        // 判断是否还有库存,如果没有了直接返回已抢光
        if (stockRepository.getStock() <= 0){
            rs.put("code",4001);
            rs.put("msg","已抢光");
            return rs;
        }
        final String orderId = UUID.randomUUID().toString();
        Order order = new Order();
        order.setOrderNo(orderId);
        order.setOrderAmount(100.0);
        order.setOrderDescription("LagouPhone秒杀");
        order.setOrderStatus(0);
        order.setUserId(userId);
        // 扣减库存
        stockRepository.decrStock();
        // 发送到消息队列里面去
        rocketMQTemplate.convertAndSend("seckill_queue", JSON.toJSON(order));
        rs.put("code",0);
        rs.put("orderId",orderId);
        rs.put("msg","下单成功");
        return rs;
    }

    /**
     *
     * @return
     */
    @RequestMapping("/toPay")
    @ResponseBody
    public Map<String,Object> toPay(String orderId){
        Map<String,Object> rs = new HashMap<>();
        if (StringUtils.isEmpty(orderId)){
            rs.put("code",4001);
            rs.put("msg","订单号不能为空");
            return rs;
        }
        // 如果查不到该订单，返回订单号有误
        if (!stockRepository.existsOrderNo(orderId)){
            rs.put("code",4002);
            rs.put("msg","订单号不存在");
            return rs;
        }
        // 如果该订单的已经支付过了,则返回已支付,否则往下走
        if (stockRepository.existsPayedByOrderNo(orderId)){
            rs.put("code",4003);
            rs.put("msg","该订单已经支付了,无须重复支付");
            return rs;
        }
        // 如果该订单已经被超时取消了,则返回已被超时取消
        if (stockRepository.existsCancelledOrderNo(orderId)){
            rs.put("code",4004);
            rs.put("msg","该订单已被超时取消了");
            return rs;
        }
        rs.put("code",0);
        rs.put("msg","支付成功");
        // 发消息给rocketmq,消费端去更新数据库状态&&将订单号写入已支付列表
        rocketMQTemplate.convertAndSend("seckill_queue_payed", orderId);
        return rs;
    }
}
